import axios from 'axios'
import { ref } from 'vue';
import { CONFIG } from '../config/index.js';
import router from '../router/index.js'
import { ElMessage, ElLoading } from 'element-plus';
let loadingInstance = ref()
axios.interceptors.request.use(function (config){
    loadingInstance.value = ElLoading.service({
        text: '正在加载中'
    })
    console.log("请求拦截器:",config)
    if(config.method == "get"){
        let timeStamp = (new Date()).getTime()
        console.log("timeStamp:", timeStamp)
        if (config.params){
            config.params.timeStamp = timeStamp
        }else{
            config.params={
                timeStamp: timeStamp
            }
        }
    }
    let TokenValue = ""
    try {
        TokenValue = window.localStorage.getItem(CONFIG.TOKEN_NAME)
    } catch(error) {
        TokenValue = ""
    }
    if(TokenValue ==""|| TokenValue==null){
        config.headers[CONFIG.TOKEN_NAME]
    }else{
        config.headers[CONFIG.TOKEN_NAME]=TokenValue
    }
    return config;
},function (error){
    ElMessage({
        type: "error",
        message: "请求错误" + error.message
    })
    return Promise.reject(error);
});

axios.interceptors.response.use(function(response){
    console.log("response:",response)
    if (response.data.status === 200){
        loadingInstance.value.close()
        return Promise.resolve(response)
    } else if(response.data.status === 401) {
        ElMessage({
            type: "warning",
            message: response.data.message
        })
        window.localStorage.removeItem(CONFIG.TOKEN_NAME)
        router.currentRoute.path != "/login" && router.replace("/login")
        loadingInstance.value.close()
    }
    return response;
}, function(error){
    ElMessage({
        type: "error",
        message: "请求错误" + error.message
    })
    return Promise.reject(error);
});


const request = (url='',data={},method="get",timeout=5000)=>{
    console.log("使用封装函数去处理请求")
    return new Promise((resolve,reject)=>{
        console.log("使用axios请求接口")
        const methodLower=method.toLowerCase()
        if(methodLower==='get'){
            axios({
                method: methodLower,
                params: data,
                timeout: timeout,
                url: url
            }).then((response)=>{
                resolve(response)
            }).catch((error)=>{
                reject(error)
            })
        }else if(methodLower==="post"){
            axios({
                method: methodLower,
                params: data,
                timeout: timeout,
                url: url
            }).then((response)=>{
                resolve(response)
            }).catch((error)=>{
                reject(error)
            })
        }
    })
}

export default request